import { defineStore } from 'pinia';
import { ref } from 'vue';
import {
    // phoneLogin as phoneLoginApi,
    getUserInfo as getUserInfoApi,
    // psdLogin as psdLoginApi,
    logout as logoutApi,
    getCsInfo as getCsInfoApi,
    bindRegId,
    // updatePwdByPhone,
} from '@/api';
import type { smsLoginType, accountLoginType, updatePasswordType } from '@/api';
// import defaultAvatar from "@/static/default_avatar.png";
import { setCache, getCache } from '@/utils';
import { global } from '@/store';

export const user = defineStore('user', () => {
    const userInfo = ref(getCache('userInfo') || {});
    const csInfo = ref(getCache('csInfo') || {});
    const token = ref(getCache('token') || '');

    // const { clear: chatClear } = chat();
    const { getDicts } = global();

    // const phoneLogin = async (data: smsLoginType) => {
    //     await beforeLogin();
    //     const res = await phoneLoginApi(data);
    //     token.value = res.data;
    //     setCache('token', res.data);
    //     await afterLogin();
    // };

    // const accordLogin = async (data: accountLoginType) => {
    //     await beforeLogin();
    //     const res = await psdLoginApi(data);
    //     token.value = res.data;
    //     setCache('token', res.data);
    //     await afterLogin();
    // };

    // const updatePassword = async (data: updatePasswordType) => {
    //     await updatePwdByPhone(data);
    // };

    // const beforeLogin = async () => {
    //     // chatClear();
    //     await clear();
    // };

    const afterLogin = async () => {
        await Promise.allSettled([getUserInfo(), getDicts()]);
        // getCsInfo(); // 需等待用户信息加载完毕
    };

    const logout = async () => {
        // #ifdef APP-PLUS
        if (getCache('registerID')) {
            await bindRegId({
                registrationId: getCache('registerID'),
                type: 2,
            });
        }
        // #endif
        await logoutApi();
        clear();
        uni.reLaunch({
            url: '/pages/login/index',
        });
    };

    const getUserInfo = async () => {
        const res = await getUserInfoApi();
        userInfo.value = res.data;
        setCache('userInfo', res.data);
        return res.data;
    };

    const getCsInfo = async () => {
        const res = await getCsInfoApi(userInfo.value.id);
        csInfo.value = res.data;
        setCache('csInfo', res.data);
        return res.data;
    };

    const clear = async () => {
        token.value = '';
        userInfo.value = {};
        csInfo.value = {};
        await uni.clearStorageSync();
    };

    return {
        userInfo,
        csInfo,
        token,
        // setInfo,
        // login,
        // phoneLogin,
        // accordLogin,
        // updatePassword,
        getUserInfo,
        getCsInfo,
        logout,
        clear,
        afterLogin,
    };
});
